package com.demo.common;

import com.demo.utils.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@RestController
@CrossOrigin
@RequestMapping("/common")
public class CommonController {
    @Value("${image.path}")
    private String basePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {

        //获取原始文件名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        //截取后缀.jpg
        String sufffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件的名称防止出现文件名相同造成的文件覆盖
        String fileName = UUID.randomUUID().toString() + sufffix;

        File dis = new File(basePath);
        if (!dis.exists()) {
            dis.mkdirs();
        }

        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删陈
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(fileName);
        return Result.success(fileName);
    }


    @GetMapping("/download/{name}")
    public void download(HttpServletResponse response, @PathVariable("name") String name) {

        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流，通过输出流将文件写回浏览器，在浏览器展示图片了
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("img/jpej");
            int len = 0;
            byte[] bytes = new byte[1024];

            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
    }
}
